<?php

use Illuminate\Support\Facades\App;

/**
 * localizedFormat.
 *
 * @param string $key
 *
 * $strdate is a datetime converted in string
 * $key is one of the keys of format arrays defined coreapi.php
 *   ('date', 'time', 'datetime')
 */
function localizedFormat(string $strdate, string $key): string
{
  $locale = App::getLocale();
  $fallbackLocale = config('app.fallback_locale');
  $availableLocales = config('coreapi.supported_locales');

  if (!in_array($locale, $availableLocales)) {
    $locale = $fallbackLocale;
  }
  $formats = config('coreapi.' . $locale);

  return date($formats[$key], strtotime($strdate));
}

/**
 * Create query parameters in correct format.
 *
 * @param array $fields
 *
 * $fields is an array which contains where parameters
 * If not passed it will return an array with just active
 * flag set according to coreapi.php.
 */
function create_qry_params(array $fields = []): array
{
  $results = [];
  $operators = config('parameters.operators');
  $oper = '=';

  $filterForActive = config('coreapi.filter_active');
  if (isset($filterForActive) && $filterForActive) {
    $results[] = ['active', '=', true];
  }
  foreach ($fields as $key => $value) {
    $oper = '=';
    foreach ($operators as $operkey => $opervalue) {
      if (false !== strpos($value, '[' . $operkey . ']')) {
        $oper = $opervalue;
        if ('like' == $oper) {
          $value = '%' . substr($value, 4) . '%';
        } else {
          $value = substr($value, 4);
        }
        break;
      }
    }
    $results[] = [$key, $oper, $value];
  }
  return $results;
}
